import talib
from django.core.serializers import serialize
from django.db.models import QuerySet, Count
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import *
import os, json
import pandas as pd
from pylab import *
import tushare as ts
from django.core import serializers


# Create your views here.
def index(request):
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)

    result = TusharDate.objects.values('tscode').annotate(Count=Count('tscode')).order_by()
    # print(type(result))
    # print(result)

    for obj in result:
        # print(obj)
        data_list.append(obj)

    # for i in range(0, len(book_list)):
    #     #data_list.append(book_list[i][9])
    #     print(i)
    # print(book_list.count())

    print("json:" + json.dumps(data_list))
    print(data_list)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'chartstest/index.html', {"dataList": json.dumps(data_list, ensure_ascii=False)})

    # 以下为查询，有专用的方式，比如
    # 实现where子名，作为方法filter()、exclude()、get()的参数
    # 语法：属性名称__比较运算符=值
    # 表示两个下划线，左侧是属性名称，右侧是比较类型
    # 对于外键，使用“属性名_id”表示外键的原始值
    # 转义：like语句中使用了%与，匹配数据中的%与，在过滤器中直接写，例如：filter(title__contains="%")=>where title like '%\%%'，表示查找标题中包含%的

    # 返回列表
    # list  = BookInfo.books1.filter(heroinfo__hcontent__contains="六")    # 包含 六 的书
    # 等价于 select * from bookinfo inner join booktest_heroinfo on bookinfo.id=book_id;
    # 是查 heroinfo 的 hcontent 中包含 六 的英雄对应的书 （BookInfo）
    # list = BookInfo.books1.aggregate(Max('id'))
    # context = {'list': list}
    # return render(request, 'booktest/public.html', context)

    # list = BookInfo.books1.filter(pk__lt=3).

    # context = {'list': list}
    # return render(request, 'booktest/public.html', context)

    # 使用aggregate()函数返回聚合函数的值
    # 函数：Avg，Count，Max，Min，Sum
    # Max1 = BookInfo.books1.aggregate(Max('id'))           # id 的最大值
    # Max1 = BookInfo.books1.aggregate(Max('bpub_data'))      # bpub_data 的最大值
    # Max1 = BookInfo.books1.aggregate(Sum('id'))
    #
    #
    # list1 = BookInfo.books1.filter(bread__gt=10)            # 阅读量大于10
    #
    #
    # # 两个列做自己算使用 F 对象，列比较，列计算等
    # list1 = BookInfo.books1.filter(bread__gt=F('bcommet'))  # 阅读量大于评论量
    #
    #
    # # 逻辑与关系
    # list1 = BookInfo.books1.filter(pk__lt=4, btitle__contains='1')
    # list1 = BookInfo.books1.filter(pk__lt=4).filter(btitle__contains='1')
    #
    # # 逻辑或使用 Q 对象
    #
    # list1 = BookInfo.books1.filter(( Q(pk__lt=6) | Q(bcommet__gt=10) ))
    # context = {'list1': list1
    #             , 'Max1': Max1
    #            }
    # return render(request, 'booktest/public.html', context)


# 在处理函数加此装饰器即可
@csrf_exempt
def jsonDate(request):
    tscode = request.POST['tscode']
    tusharDates = TusharDate.objects.filter(tscode=tscode)
    # print(tusharDates)

    # ret = models.TusharDate.objects.all().order_by("dayIncome", "id")
    ret1 = serialize("json", tusharDates)
    retList = json.loads(ret1)
    # print(retList)
    ret2 = []
    print('---------------------')
    for num in range(len(retList)):
        fields = retList[num]['fields']
        fields.update(id=retList[num]['pk'])
        ret2.append(fields)
        # print(ret2)

    data = {'status': 0, 'dates': ret2}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")


# 计算查询结果
# 在处理函数加此装饰器即可
@csrf_exempt
def computedResult(request):
    # 参数
    tscode = request.POST['tscode']
    startTime = request.POST['startTime']
    endTime = request.POST['endTime']
    macdF = request.POST['macdF']
    macdSL = request.POST['macdSL']
    macdSI = request.POST['macdSI']
    buy = request.POST['buy']
    sell = request.POST['sell']

    ls = json.dumps(tscode, ensure_ascii=False)
    info = HttpResponse(ls)

    # 下面这两行设置夸域请求，跨域就是用这两行
    # info['Access-Control-Allow-Origin'] = '*'
    # info['Access-Control-Allow-Headers'] = "Content-Type"
    if tscode == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    if startTime == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    if endTime == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    startTime = startTime.replace('-', '')
    endTime = endTime.replace('-', '')
    print(startTime + endTime)
    pro = ts.pro_api('a2c606601f02e667f405b59da6f34ecf6d00581d62a9e3cf831bb16b')

    # 使用ggplot样式，好看些
    # mpl..style.use("ggplot")
    # 获取上证指数数据
    # data = ts.get_k_data("000001", index=True, start="2019-01-01")
    ts_code = '600575.SH'
    start_date = '20180701'
    end_date = '20191024'
    f = 6
    s = 12
    si = 9
    #
    if macdF != '':
        f = int(macdF)
    if macdSL != '':
        s = int(macdSL)

    if macdSI != '':
        si = int(macdSI)

    # print(type(macdF))
    #从tushare查询某只股票日线数据
    data = pro.daily(ts_code=tscode, start_date=startTime, end_date=endTime)
    pd.set_option('display.max_columns', None)
    # if data is None:
    #     return info

    # 将date值转换为datetime类型，并且设置成index
    data.trade_date = pd.to_datetime(data.trade_date)
    data.index = data.trade_date

    # 计算MACD指标数据
    #然后按照下面的原则判断买入还是卖出。
    #1. DIFF、DEA均为正，DIFF向上突破DEA，买入信号。
    #2. DIFF、DEA均为负，DIFF向下跌破DEA，卖出信号。
    #3.DEA线与K线发生背离，行情反转信号。
    #4.分析MACD柱状线，由正变负，卖出信号；由负变正，买入信号。

    #macd（对应diff），
    #macdsignal（对应dea），
    #macdhist（对应macd）。
    data["DIFF"], data["DEA"], data["MACD"] = talib.MACD(data.close, fastperiod=f, slowperiod=s, signalperiod=si)
    # 计算移动平均线
    #data["ma10"] = talib.MA(data.close, timeperiod=10)
    #data["ma30"] = talib.MA(data.close, timeperiod=30)

    # 计算RSI
    # data["rsi"] = talib.RSI(data.close)

    # 计算MACD指标数据
    # data["macd"], data["sigal"], data["hist"] = talib.MACD(data.close)

    # dataform 转成list
    train_data = np.array(data)  # np.ndarray()
    train_x_list = train_data.tolist()  # list

    #数据排序，正序
    train_x_list.sort(reverse=False)
    print(train_x_list)
    # 买点
    bu = 0
    # 卖点
    se = 0

    #       buy,sell
    if buy != '':
        bu = int(buy)
    if sell != '':
        se = int(sell)

    total = 0
    a = 0
    b = 0
    buyPrice = 0.00
    sellPrice = 0.00
    success_ratio = 0.00
    buyTime = ""
    sellTime = ""

    dealDetailList = []
    #ts_code 股票代码 0
    #trade_date 交易日期 1
    #open 开盘价 2
    #high 最高价 3
    #low 最低价 4
    #close 收盘价 5
    #pre_close 昨收价 6
    #change 涨跌额 7
    #pct_chg 涨跌幅 8
    #vol 成交量 （手）9
    #amount 成交额 （千元） 10
    #DIFF 11
    #DEA 12
    # MACD 13
    # ma10  14
    # ma30  15

    for i in range(1, len(train_x_list)-1):
        result = 0.00
        # print(train_x_list[i])
        #开盘价
        open = train_x_list[i][2]
        close = train_x_list[i][5]
        # 均价
        avg = train_x_list[i][4]
        #
        DIFF = float(train_x_list[i][11])
        DEA = float(train_x_list[i][12])
        #收盘价


        open2 = train_x_list[i - 1][2]
        macd2 = float(train_x_list[i - 1][11])
        sigal2 = float(train_x_list[i - 1][12])
        close2 = train_x_list[i - 1][5]

        open3 = train_x_list[i + 1][2]
        macd3 = float(train_x_list[i + 1][11])
        sigal3 = float(train_x_list[i + 1][12])
        close3 = train_x_list[i + 1][5]

        if (macd2 != macd2):
            continue

        # macd sigal 买点 交叉点判断，前一天数值macd的值大于sigal2，后一天数据macd小于sigal
        if (macd3 < sigal3 and macd2 > sigal2):
            # buy=open
            # 买入时间
            buyTime = train_x_list[i + bu][1]
            # 买入价格
            buyPrice = float(train_x_list[i + bu][2])
            print("买点：buy" + str(buyPrice) + "第" + str(train_x_list[i + 1][1]))
        # macd sigal 卖点  交叉点判断，前一天数值macd的值小于sigal2，后一天数据macd大于sigal
        if (macd3 > sigal3 and macd2 < sigal2):
            # sell=open
            # 卖出时间
            sellTime = train_x_list[i + se][1]
            # 卖出价格
            sellPrice = float(train_x_list[i + se][2])
        if (buyPrice != 0.00 and sellPrice != 0.00):
            result = sellPrice - buyPrice
            if (result > 0):
                b = b + 1

            print("卖点：" + str(sellPrice) + "开盘价差价：" + str(result) + "第" + str(train_x_list[i][1]))

            a = a + 1
            # 添加交易详细信息表
            dealDetail = DealDetail()
            dealDetail.tscode = tscode
            dealDetail.buyTime = buyTime
            dealDetail.sellTime = sellTime
            dealDetail.buyPrice = buyPrice
            dealDetail.sellPrice = sellPrice
            dealDetail.tradProfit = round(result, 3)
            dealDetailList.append(dealDetail)
            # tusharDate.dealdetail_set.add(dealDetail)


            buyPrice = 0.00
            sellPrice = 0.00

        total = total + result
        if (a != 0):
            success_ratio = round((b / a) * 100, 3)

    tusharDate = TusharDate()
    tusharDate.tscode = tscode
    tusharDate.macdF = f
    tusharDate.macdSI = s
    tusharDate.macdSL = si
    tusharDate.startTime = startTime
    tusharDate.endTime = endTime
    tusharDate.buy = buy
    tusharDate.sell = sell
    tusharDate.tradProfit = round(total, 3)
    tusharDate.successRatio = success_ratio

    if tusharDate:
        print(tusharDate.successRatio)
        tusharDate.save()
        for i in range(0, len(dealDetailList)):
            dealDetail = dealDetailList[i]
            dealDetail.tusharDate_id = tusharDate.id
            dealDetail.save()

    return info


# 详细信息
@csrf_exempt
def detail(request):
    print("--------------------------------------详细信息")
    # 参数
    id = request.GET['id']
    data_list = []
    result = DealDetail.objects.filter(tusharDate_id=id)

    ret1 = serialize("json", result)
    retList = json.loads(ret1)

    for num in range(len(retList)):
        fields = retList[num]['fields']
        fields.update(id=retList[num]['pk'])
        data_list.append(fields)
        # print(ret2)


    print("json:" + json.dumps(data_list))

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'chartstest/details.html', {"detailList": json.dumps(data_list, ensure_ascii=False)})
